package org.ligson.hbase127.core;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.data.repository.core.EntityInformation;

import java.lang.reflect.Field;

public class HBaseEntityInformation<T, ID> implements EntityInformation<T, ID> {
    private Class<T> domainClass;

    public HBaseEntityInformation(Class<T> domainClass) {
        this.domainClass = domainClass;
    }

    @Override
    public boolean isNew(T entity) {
        Field[] fields = entity.getClass().getDeclaredFields();
        for (Field field : fields) {
            org.ligson.hbase127.fw.ID id = field.getDeclaredAnnotation(org.ligson.hbase127.fw.ID.class);
            if (id != null) {
                try {
                    Object obj = PropertyUtils.getProperty(entity, field.getName());
                    if (obj != null) {
                        return false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    @Override
    public ID getId(T entity) {
        Field[] fields = entity.getClass().getDeclaredFields();
        for (Field field : fields) {
            org.ligson.hbase127.fw.ID id = field.getDeclaredAnnotation(org.ligson.hbase127.fw.ID.class);
            if (id != null) {
                try {
                    Object obj = PropertyUtils.getProperty(entity, field.getName());
                    return (ID) obj;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    public Class<ID> getIdType() {
        Field[] fields = domainClass.getDeclaredFields();
        for (Field field : fields) {
            org.ligson.hbase127.fw.ID id = field.getDeclaredAnnotation(org.ligson.hbase127.fw.ID.class);
            if (id != null) {
                return (Class<ID>) field.getType();
            }
        }
        return null;
    }

    @Override
    public Class<T> getJavaType() {
        return domainClass;
    }
}
